const Router = require("koa-router");
const R = require("../app/R");

const userDao = require("../dao/UserDao");

const UserRouter = new Router({ prefix: "/user" });

UserRouter.post("/save", async (ctx, next) => {
  const data = ctx.request.body;

  if (data.PhoneNumber) {
    const result = await userDao.getOneByPhoneNumber(data.PhoneNumber);
    if (result != null) {
      ctx.body = new R().setIsSuccess(false).setMessage("电话号码已注册过！");
      return;
    }
  }

  const result = await userDao.save(data);
  ctx.body = new R().setResult({
    User: result,
  });
});

UserRouter.post("/getUserInfo", async (ctx, next) => {
  const data = ctx.request.body;
  if (data.UserId) {
    const result = await userDao.getOneById(data.UserId);
    ctx.body = new R().setResult({
      User: result,
    });
  }
  if (data.PhoneNumber) {
    const result = await userDao.getOneByPhoneNumber(data.PhoneNumber);
    ctx.body = new R().setResult({
      User: result,
    });
  }
});

UserRouter.post("/getUserBaseInfo", async (ctx, next) => {
  const data = ctx.request.body;
  const result = await userDao.getUserBaseInfo(data.UserId);
  ctx.body = new R().setResult({
    User: result,
  });
});

UserRouter.post("/updataUserBaseInfo", async (ctx, next) => {
  const data = ctx.request.body;
  console.log(data);
  const result = await userDao.update(data);

  ctx.body = new R().setResult({
    User: result,
  });
});

module.exports = UserRouter;
